import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
import { Restaurant } from '../entities/restaurant.entity';
import { DrawHistory } from '../entities/draw-history.entity';
import { RestaurantMark } from '../entities/restaurant-mark.entity';

export const getDatabaseConfig = (
  configService: ConfigService,
): TypeOrmModuleOptions => {
  const dbType = configService.get<string>('DB_TYPE', 'sqlite');

  const baseConfig = {
    entities: [Restaurant, DrawHistory, RestaurantMark],
    synchronize: configService.get<boolean>('DB_SYNCHRONIZE', true),
    logging: configService.get<boolean>('DB_LOGGING', false),
  };

  if (dbType === 'sqlite') {
    return {
      ...baseConfig,
      type: 'sqlite',
      database: configService.get<string>('DB_DATABASE', 'whatToEat.db'),
    };
  }

  if (dbType === 'mysql') {
    return {
      ...baseConfig,
      type: 'mysql',
      host: configService.get<string>('DB_HOST', 'localhost'),
      port: configService.get<number>('DB_PORT', 3306),
      username: configService.get<string>('DB_USERNAME', 'root'),
      password: configService.get<string>('DB_PASSWORD', ''),
      database: configService.get<string>('DB_DATABASE', 'whatToEat'),
    };
  }

  if (dbType === 'postgres') {
    return {
      ...baseConfig,
      type: 'postgres',
      host: configService.get<string>('DB_HOST', 'localhost'),
      port: configService.get<number>('DB_PORT', 5432),
      username: configService.get<string>('DB_USERNAME', 'postgres'),
      password: configService.get<string>('DB_PASSWORD', ''),
      database: configService.get<string>('DB_DATABASE', 'whatToEat'),
    };
  }

  // 默认使用 SQLite
  return {
    ...baseConfig,
    type: 'sqlite',
    database: 'whatToEat.db',
  };
};
